/**
 * This file is part of 1genia trampoline
 * Copyright (C) 2007 - 2008 1genia (contact@1genia.com)
 *
 * This library is free software; you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as
 * published by the Free Software Foundation; version 3 of the License. 
 *
 * This library is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details. 
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; see the file COPYING.TXT.  If not,
 * write to the Free Software Foundation, Inc., 51 Franklin Street,
 * Fifth Floor, Boston, MA 02110-1301, USA. 
 **/
package com.genia.toolbox.projects.csv.business.manager.impl;

import java.io.File;
import java.io.FileFilter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import com.genia.toolbox.basics.exception.technical.TechnicalException;
import com.genia.toolbox.basics.manager.ExceptionManager;
import com.genia.toolbox.projects.csv.bean.CsvVersion;
import com.genia.toolbox.projects.csv.bean.FolderDescriptor;
import com.genia.toolbox.projects.csv.bean.MappingDescriptor;
import com.genia.toolbox.projects.csv.bean.MutableCsvVersion;
import com.genia.toolbox.projects.csv.bean.impl.CsvVersionImpl;
import com.genia.toolbox.projects.csv.business.manager.CsvVersionManager;

/**
 * the implementation class of {@link CsvVersionManager}.
 */
public class CsvVersionManagerImpl
    implements CsvVersionManager
{
  /**
   * the date format.
   */
  public static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");

  /**
   * identify the version number.
   */
  private static final String VERSION_ID = "@version@";

  /**
   * identifier the string date.
   */
  private static final String DATE_ID = "@date@";

  /**
   * the extension of the file.
   */
  public static final String EXTENSION = "csv";

  /**
   * the pattern of the version.
   */
  private static final String PATTERN = VERSION_ID + "_" + DATE_ID + "." + EXTENSION;

  /**
   * the {@link ExceptionManager} to use.
   */
  private ExceptionManager exceptionManager;



  /**
   * get the {@link List} of existing {@link CsvVersion}s regarding to the
   * given {@link MappingDescriptor} object.
   * 
   * @param mappingDescriptor
   *          the {@link MappingDescriptor} that describes the mapping
   * @param basePath
   *          the {@link File} representation of the path to the base folder
   * @return a {@link List} of {@link CsvVersion}s
   * @throws TechnicalException
   *           if an io error occur
   */
  public List<CsvVersion> getVersions(MappingDescriptor mappingDescriptor, File basePath)
      throws TechnicalException
  {
    Set<CsvVersion> versionSet = new TreeSet<CsvVersion>();
    for (FolderDescriptor folder : mappingDescriptor.getFolders()) {
      File folderPath = new File(basePath, folder.getFolderName());
      if (folderPath.exists()) {
        File[] arrayFiles = folderPath.listFiles(new FileFilter()
        {
          public boolean accept(File pathname)
          {
            boolean response = false;
            if (pathname.getName().endsWith(".csv")) {
              response = true;
            }
            return response;
          }

        });
        List<File> files = Arrays.asList(arrayFiles);
        for (File file : files) {
          versionSet.add(parse(file.getName()));
        }

      }

    }
    return new ArrayList<CsvVersion>(versionSet);
  }



  /**
   * get the last csv version.
   * 
   * @param mappingDescriptor
   *          the {@link MappingDescriptor} that describes the mapping
   * @param basePath
   *          the {@link File} representation of the path to the base folder
   * @return the last {@link CsvVersion} or null if no version exist
   * @throws TechnicalException
   *           if an io error occur
   */
  public CsvVersion getLastVersion(MappingDescriptor mappingDescriptor, File basePath)
      throws TechnicalException
  {
    CsvVersion lastVersion = null;
    List<CsvVersion> versions = this.getVersions(mappingDescriptor, basePath);
    if (versions.size() > 0) {
      lastVersion = versions.get(versions.size() - 1);
    }
    return lastVersion;

  }



  /**
   * get the new csv version.
   * 
   * @param mappingDescriptor
   *          the {@link MappingDescriptor} that describes the mapping
   * @param basePath
   *          the {@link File} representation of the path to the base folder
   * @return the new {@link CsvVersion}
   * @throws TechnicalException
   *           if an io error occur TechnicalException
   */
  public CsvVersion getNewVersion(MappingDescriptor mappingDescriptor, File basePath)
      throws TechnicalException
  {
    MutableCsvVersion newVersion = new CsvVersionImpl();
    newVersion.setVersionDate(new Date());

    CsvVersion lastVersion = this.getLastVersion(mappingDescriptor, basePath);
    if (lastVersion != null) {
      newVersion.setVersionNumber(new Integer(lastVersion.getVersionNumber().intValue() + 1));
    }
    else {
      newVersion.setVersionNumber(new Integer(1));
    }
    return newVersion;

  }



  /**
   * for getting the corresponding file name to the given {@link CsvVersion}
   * object.
   * 
   * @param version
   *          the {@link CsvVersion} to format.
   * @return the corresponding file name to the given {@link CsvVersion} object
   */
  public String format(CsvVersion version)
  {
    String strDate = DATE_FORMAT.format(version.getVersionDate());
    String strVersionFile = PATTERN.replaceAll(VERSION_ID, version.getVersionNumber().toString()).replaceAll(DATE_ID, strDate);
    return strVersionFile;

  }



  /**
   * for getting the corresponding {@link CsvVersion} object to the given file
   * name.
   * 
   * @param strVersionFile
   *          the formated file name
   * @return a {@link CsvVersion} object
   * @throws TechnicalException
   *           if a parse error occur
   */
  public CsvVersion parse(String strVersionFile)
      throws TechnicalException
  {
    try {
      MutableCsvVersion result = null;
      if (!strVersionFile.endsWith("." + EXTENSION)) {
        throw new ParseException("wrong extension file : " + strVersionFile, 0);
      }
      String nameOnly = strVersionFile.replaceAll("." + EXTENSION, "");
      int index = nameOnly.indexOf("_");
      if (index > 0) {
        String strVersion = nameOnly.substring(0, index);
        String strDate = nameOnly.substring(index + 1);
        result = new CsvVersionImpl();
        result.setVersionNumber(new Integer(strVersion));
        result.setVersionDate(DATE_FORMAT.parse(strDate));
      }
      else {
        throw new ParseException("error format : " + strVersionFile, 1);
      }

      return result;
    }
    catch (Exception e) {
      throw getExceptionManager().convertException(e);
    }
  }



  /**
   * getter for the exceptionManager property.
   * 
   * @return the exceptionManager
   */
  public ExceptionManager getExceptionManager()
  {
    return exceptionManager;
  }



  /**
   * setter for the exceptionManager property.
   * 
   * @param exceptionManager
   *          the exceptionManager to set
   */
  public void setExceptionManager(ExceptionManager exceptionManager)
  {
    this.exceptionManager = exceptionManager;
  }
}
